package com.hengxinguotong.zhihuichengjian.fragment;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.UserInfo;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.ArticleListActivity;
import com.hengxinguotong.zhihuichengjian.ui.MainActivity;
import com.hengxinguotong.zhihuichengjian.ui.SettingsActivity;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.ui.app.MyApp;
import com.hengxinguotong.zhihuichengjian.uitool.ShareBoard;
import com.hengxinguotong.zhihuichengjian.uitool.ShareBoardlistener;
import com.hengxinguotong.zhihuichengjian.uitool.SnsPlatform;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.CircleImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.android.api.PlatActionListener;
import cn.jiguang.share.android.api.Platform;
import cn.jiguang.share.android.api.ShareParams;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.qqmodel.QZone;
import cn.jiguang.share.wechat.Wechat;
import cn.jiguang.share.wechat.WechatFavorite;
import cn.jiguang.share.wechat.WechatMoments;
import cn.jiguang.share.weibo.SinaWeibo;
import cn.jiguang.share.weibo.SinaWeiboMessage;

/**
 * 我的
 */
public class MyFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.name_tv)
    HXTextView nameTv;
    @BindView(R.id.position_tv)
    HXTextView positionTv;
    @BindView(R.id.mobile_tv)
    HXTextView mobileTv;
    @BindView(R.id.company_tv)
    HXTextView companyTv;
    @BindView(R.id.ll_attention)
    LinearLayout llAttention;
    @BindView(R.id.ll_record)
    LinearLayout llRecord;
    @BindView(R.id.ll_alter)
    LinearLayout llAlter;
    @BindView(R.id.ll_exit)
    LinearLayout llExit;
    @BindView(R.id.address_tv)
    HXTextView addressTv;
    @BindView(R.id.avater_iv)
    CircleImageView avaterIv;
    Unbinder unbinder;
    private View rootView = null;
    private UserInfo userInfo;
    private MainActivity mActivity;
    private Intent intent;
    private ProgressDialog progressDialog;
    private ShareBoard mShareBoard;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String toastMsg = (String) msg.obj;
            Toast.makeText(mActivity, toastMsg, Toast.LENGTH_SHORT).show();
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        }
    };
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.my_fragment, null);
            unbinder = ButterKnife.bind(this, rootView);
            mActivity = (MainActivity) getActivity();
            progressDialog = new ProgressDialog(mActivity);
            progressDialog.setTitle("请稍候");
            String json = SPUtil.getString(mActivity, "json");
            if(null != json && !Utils.isEmpty(json)){
                userInfo = new Gson().fromJson(json, UserInfo.class);
                if (null != userInfo.value) {
                    addressTv.setText(userInfo.value.getLevelName());
                    nameTv.setText(userInfo.value.getRealName());
                    if(null != userInfo.value.getPerson()){
                        Glide.with(mActivity)
                                .load(userInfo.value.getPerson().getHeadPortrait())
                                .placeholder(R.mipmap.icon_avater_defalut)
                                .error(R.mipmap.icon_avater_defalut)
                                .into(avaterIv);
                        companyTv.setText(userInfo.value.getPerson().getProjectCompanyName());
                        mobileTv.setText(userInfo.value.getPerson().getMobile());
                        positionTv.setText(userInfo.value.getPerson().getPositionWorktype());
                    }
                }
            }
        } else {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if(Build.VERSION.SDK_INT >= 23){
            if(ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.READ_EXTERNAL_STORAGE ) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            }
        }
    }

    @Override
    public void onLazyLoad() {

    }

    //提示对话框

    //    private void showDialog() {
//        Typeface lantypeFace = Utils.getTypeface(getActivity());
//        Typeface typeFace = Utils.getTypeface(getActivity());
//        CustomPatient.Builder builder = new CustomPatient.Builder(getActivity());
//        builder.setContent("退出登录", lantypeFace, typeFace);
//        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                //设置你的操作事项
//            }
//        });
//        builder.setNegativeButton("确定",
//                new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//
//                        Utils.loginOut(getActivity());
//                        Toast.makeText(getActivity(), "退出成功", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//        CustomPatient CustomPatient = builder.create();
//        CustomPatient.show();
//        Window window = CustomPatient.getWindow();
//        WindowManager m = getActivity().getWindowManager();
//        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
//        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
//        p.height = (int) (d.getHeight() * 0.20); // 宽度设置为屏幕的0.20
//        p.width = (int) (d.getWidth() * 0.70); // 宽度设置为屏幕的0.65
//        window.setAttributes(p);
//    }
    @Override
    public void onStop() {
        super.onStop();
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.ll_exit, R.id.avater_iv, R.id.ll_alter, R.id.ll_record, R.id.ll_attention})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_exit:
//                new Handler().post(new Runnable() {
//                    @Override
//                    public void run() {
//                        showDialog();
//                    }
//                });
                break;
            case R.id.avater_iv:
                if (userInfo != null && userInfo.value != null && userInfo.value.getPerson().getHeadPortrait() != null) {
                    ArrayList<String> paths = new ArrayList<String>();
                    paths.add(userInfo.value.getPerson().getHeadPortrait());
                    TaskBigImgActivity.startActivity(getActivity(), paths, 0);
                }
                break;
            case R.id.ll_alter:
                intent = new Intent();
                intent.setClass(mActivity, SettingsActivity.class);
                startActivity(intent);
//                mActivity.finish();
                break;
            case R.id.ll_record:
//                Toast.makeText(mActivity, "功能开发中，敬请期待…", Toast.LENGTH_LONG ).show();
                showBroadView();
                break;
            case R.id.ll_attention:
//                Toast.makeText(mActivity, "功能开发中，敬请期待…", Toast.LENGTH_LONG ).show();
                intent = new Intent();
                intent.setClass(mActivity, ArticleListActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void showBroadView() {
        if (mShareBoard == null) {
            mShareBoard = new ShareBoard(mActivity);
            List<String> platforms = JShareInterface.getPlatformList();
            if (platforms != null) {
                Iterator var2 = platforms.iterator();
                while (var2.hasNext()) {
                    String temp = (String) var2.next();
                    if(!temp.equals("WechatFavorite")){//屏蔽微信收藏
                        SnsPlatform snsPlatform = createSnsPlatform(temp);
                        mShareBoard.addPlatform(snsPlatform);
                    }

                }
            }
            mShareBoard.setShareboardclickCallback(mShareBoardlistener);
        }
        mShareBoard.show();
    }

    private int mAction = Platform.ACTION_SHARE;
    public static String share_url = "http://www.escst.com/";
    public static String share_text = "提高工作效率！\n降低运营成本！\n保障生产安全！";
    public static String share_title = " 智慧城建 建筑生命管理专家";
    private ShareBoardlistener mShareBoardlistener = new ShareBoardlistener() {
        @Override
        public void onclick(SnsPlatform snsPlatform, String platform) {

            switch (mAction) {
                case Platform.ACTION_SHARE:
                    progressDialog.show();
                    //这里以分享链接为例
                    ShareParams shareParams = new ShareParams();
                    shareParams.setShareType(Platform.SHARE_WEBPAGE);//分享链接
                    shareParams.setTitle(share_title);//分享标题
                    shareParams.setText(share_text);//分享文本简介
                    shareParams.setUrl(share_url);//分享的链接
                    shareParams.setImagePath(MyApp.ImagePath);//分享的图片
                    JShareInterface.share(platform, shareParams, mShareListener);
                    break;
                default:
                    break;
            }
        }
    };

    private PlatActionListener mShareListener = new PlatActionListener() {
        @Override
        public void onComplete(Platform platform, int action, HashMap<String, Object> data) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享成功";
                handler.sendMessage(message);
            }
        }

        @Override
        public void onError(Platform platform, int action, int errorCode, Throwable error) {

            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享失败:" + error.getMessage();
                handler.sendMessage(message);
            }
        }

        @Override
        public void onCancel(Platform platform, int action) {
            if (handler != null) {
                Message message = handler.obtainMessage();
                message.obj = "分享取消";
                handler.sendMessage(message);
            }
        }
    };

    public static SnsPlatform createSnsPlatform(String platformName) {
        String mShowWord = platformName;
        String mIcon = "";
        String mGrayIcon = "";
        String mKeyword = platformName;
        if (platformName.equals(Wechat.Name)) {//微信好友
            mIcon = "jiguang_socialize_wechat";
            mGrayIcon = "jiguang_socialize_wechat";
            mShowWord = "jiguang_socialize_text_weixin_key";
        } else if (platformName.equals(WechatMoments.Name)) {//微信朋友圈
            mIcon = "jiguang_socialize_wxcircle";
            mGrayIcon = "jiguang_socialize_wxcircle";
            mShowWord = "jiguang_socialize_text_weixin_circle_key";

        } else if (platformName.equals(WechatFavorite.Name)) {//微信收藏
            mIcon = "jiguang_socialize_wxfavorite";
            mGrayIcon = "jiguang_socialize_wxfavorite";
            mShowWord = "jiguang_socialize_text_weixin_favorite_key";

        } else if (platformName.equals(SinaWeibo.Name)) {//新浪微博
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_key";
        } else if (platformName.equals(SinaWeiboMessage.Name)) {
            mIcon = "jiguang_socialize_sina";
            mGrayIcon = "jiguang_socialize_sina";
            mShowWord = "jiguang_socialize_text_sina_msg_key";
        } else if (platformName.equals(QQ.Name)) {//QQ好友
            mIcon = "jiguang_socialize_qq";
            mGrayIcon = "jiguang_socialize_qq";
            mShowWord = "jiguang_socialize_text_qq_key";

        } else if (platformName.equals(QZone.Name)) {//QQ空间
            mIcon = "jiguang_socialize_qzone";
            mGrayIcon = "jiguang_socialize_qzone";
            mShowWord = "jiguang_socialize_text_qq_zone_key";
        }
        return ShareBoard.createSnsPlatform(mShowWord, mKeyword, mIcon, mGrayIcon, 0);
    }


}
